package com.eras.shoes.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.List;

public class MacBlacklistManager {
    private Context context;
    private MacBlacklistDbHelper dbHelper;

    public MacBlacklistManager(Context context) {
        this.context = context;
        this.dbHelper = new MacBlacklistDbHelper(context);
    }

    public boolean addToBlacklist(String mac) {
        Log.e("MacBlacklistManager", "addToBlacklist="+mac);
        if (!isValidMac(mac)) {
            throw new IllegalArgumentException("Invalid MAC format");
        }
        return dbHelper.addMac(mac);
    }

    public boolean removeFromBlacklist(String mac) {
        Log.e("MacBlacklistManager", "removeFromBlacklist="+mac);
        return dbHelper.removeMac(mac);
    }

    public boolean isBlacklisted(String mac) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(MacBlacklistDbHelper.TABLE_NAME,
                new String[]{MacBlacklistDbHelper.COL_MAC},
                MacBlacklistDbHelper.COL_MAC + "=?",
                new String[]{mac}, null, null, null);
        boolean result = cursor.getCount() > 0;
        Log.e("MacBlacklistManager", "BlacklistCount="+cursor.getCount());
        cursor.close();
        return result;
    }

    private boolean isValidMac(String mac) {
        return mac.matches("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$");
    }

    public List<String> getBlacklist() {
        return dbHelper.getAllMacs();
    }

    public void removeBlacklist() {
        List<String> blacklist = getBlacklist();
        for (int i = 0; i < blacklist.size(); i++) {
            removeFromBlacklist(blacklist.get(i));
        }
    }

}

